#coding=utf-8
class BiTreeNode:
    def __init__(self, t, left=None, right=None):
        self.value = t
        self.left = left
        self.right = right


class BiTree:
    def __init__(self):
        self.root = None






class BinHeap:
    def __init__(self):
        self.heapList = [0]
        self.currentSize = 0

    def buildHeap(self,alist):
        mid = len(alist) // 2
        self.currentSize = len(alist)
        self.heapList = [0] + alist[:]
        while(mid > 0):
            self.max_heapify_rec(mid)
            mid = mid - 1

    def max_heapify_rec(self,i):
        if(i * 2) <= self.currentSize:
            mc = self.maxChild(i)
            if self.heapList[i] < self.heapList[mc]:
                self.heapList[i] , self.heapList[mc] = self.heapList[mc] , self.heapList[i]
                self.max_heapify_rec(mc)

    def maxChild(self,i):
        leftchild = i * 2
        rightchild = i * 2 + 1
        if leftchild <= self.currentSize and self.heapList[leftchild] > self.heapList[i]:
            largest = leftchild
        else:
            largest = i
        if rightchild <= self.currentSize and self.heapList[rightchild] > self.heapList[largest]:
            largest = rightchild
        return largest

    def printlist(self):
        return self.heapList[1:]

    def heapsort(self):
        sortedh = []
        while self.currentSize > 0:
            sortedh.append(self.heapList[1])
            self.heapList[1] = self.heapList[self.currentSize]
            self.heapList.pop(-1)
            self.currentSize -= 1
            self.max_heapify_rec(1)
        return sortedh

numlist =  [80,40,30,60,81,90,100,10]
_heap = BinHeap()
_heap.buildHeap(numlist)
print(f'建堆后的堆为： {_heap.printlist()}')
print(f'堆排序为： {_heap.heapsort()}')